const joi = require('joi');
const baseResp = require('./baseResp');
const errorCode = require('./errorCode');

/**
 * 参数校验
 * @param schema
 * @param options
 * @returns {Function}
 */
module.exports = (schema, options) => function (req, res, next) {
  //  参数
  const params = Object.assign(req.body, req.query, req.params);
  joi.validate(params, schema, options, (err, value) => {
    if (err) {
      let message = '';
      if (Array.isArray(err.details)) {
        console.log('xxxxxxxxxxxxxxxx', typeof err.details[0].context)
        console.log('bbbbbbb', typeof err.details[0].context.label)
        if (err.details[0].context && err.details[0].context.label) {
          message = err.details[0].context.label;
        }
      }
      console.log(message)
      return next(baseResp.error(errorCode.paramsError, message));
    }
    next();
  });
};
